package org.smile.auth.session.redis;

import org.smile.auth.session.AbstractSession;
import org.smile.auth.session.Manager;
import org.smile.auth.session.SessionListener;
import org.smile.auth.session.Store;

import java.util.Enumeration;
import java.util.Set;

/**
 * 使用redis实现持久化的session实现
 *
 * @author 胡真山
 */
public class RedisSession extends AbstractSession {

    /**
     * 持久化实现
     */
    protected Store store;

    public RedisSession(Manager manager) {
        super(manager);
    }

    public Store getStore() {
        return store;
    }

    public void setStore(Store store) {
        this.store = store;
    }

    @Override
    public Enumeration<String> getAttributeNames() {
        return this.store.getAttributeNames(this);
    }

    @Override
    public Set<String> getValueNames() {
        return this.store.getValueNames(this);
    }

    @Override
    public void invalidate() {
        expire();
        this.store.remove(this.getId());
    }

    @Override
    public boolean isNew() {
        return false;
    }

    @Override
    public void setAttribute(String name, Object value) {
        Object oldValue = getAttribute(name);
        if (value == null && oldValue != null) {
            store.removeAttribute(this, name);
        } else if (value != null) {
            store.setAttribute(this, name, value);
        }
    }

    @Override
    public void putValue(String name, Object value) {
        this.setAttribute(name, value);
    }

    /**
     * 当session的数据存贮发生变化时
     *
     * @param name
     * @param datas
     */
    protected void onAttributeStoreChange(String name, byte[] datas) {

    }

    /**
     * 在一次请求之后处理
     */
    protected void afterRequest() {

    }

    /**
     * 设置属性值 不进行持久化
     *
     * @param name
     * @param value
     */
    protected void setValue(String name, Object value) {

    }

    @Override
    public Object getAttribute(String name) {
        return store.getAttribute(this, name);
    }

    @Override
    public Object getValue(String name) {
        return getAttribute(name);
    }

    @Override
    public void access() {
        store.access(this);
    }

    @Override
    public void removeSessionListener(SessionListener listener) {

    }

    @Override
    public void removeAttribute(String name) {
        store.removeAttribute(this, name);
    }

    @Override
    public void removeValue(String name) {
        this.removeAttribute(name);
    }

    @Override
    public void initToken(String token) {
        this.setToken(token);
        this.store.saveBaseByToken(this);
    }
}
